/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package overlaynetwork;

import java.io.*;
import java.net.*;



public class createOverlay {

    private OverlayNetwork overlayNetwork;
    private BufferedReader br ;
    
    public createOverlay(OverlayNetwork overlay ){
         this.overlayNetwork = overlay;
    try{
       br = new BufferedReader(new FileReader("lista_peer.txt"));
      
       String s;
       int index=1;
       while((s=br.readLine())!=null){
           InetSocketAddress address = 
             new InetSocketAddress( s.substring(0, s.indexOf(":")), 
                                    Integer.parseInt(s.substring(s.indexOf(":")+1)));
           Peer peer = new Peer(address);
           overlay.getPeers().put(index, peer);

           
//effettuare controllo no sulla porta ma sull'ip
          
           if(overlay.getInetSocketAddress().getPort()==peer.getInetSocketAddress().getPort()){
            
               overlay.setID(index);
               }
           index++;
       }

       br.close();


       index = overlay.getID();

       int size = overlay.getPeers().size();
       int valore = (index+1)%size;
       if(valore<=0) valore += size;
       Peer peer = (Peer)overlay.getPeers().get(valore);
       overlayNetwork.connect().connect(peer.getInetSocketAddress());
       peer.connect(true);


       valore = (index+(size/4)+1)%size;
       if(size%4==0) valore = valore-1;
       if(valore<=0) valore += size;
       peer = (Peer)overlay.getPeers().get(valore);
       overlayNetwork.connect().connect(peer.getInetSocketAddress());
       peer.connect(true);


       valore = (index+(3*size/4))%size;
       if(valore<=0) valore += size;
       peer = (Peer)overlay.getPeers().get(valore);
       overlayNetwork.connect().connect(peer.getInetSocketAddress());
       peer.connect(true);
      

       valore = (index-1)%size;
       if(valore<=0) valore += size;
       peer = (Peer)overlay.getPeers().get(valore);
       overlayNetwork.connect().connect(peer.getInetSocketAddress());
       peer.connect(true);

       System.out.println("collegamenti creati");

     }catch(Exception e){
         System.err.println("ERRORE in crete_overlay");
         e.printStackTrace();
     }
    }



}
